package com.example.boot.handler;

import java.net.URI;

import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.example.boot.dao.UserRepository;
import com.example.boot.entity.User;

import reactor.core.publisher.Mono;

/**
 * 
 * @author KL 
 * @date  2018年3月2日
 * @description 业务层相当于service层
 *
 */
@Component
public class UserHandler {

	private final UserRepository userRepository;

	public UserHandler(UserRepository userRepository){
		this.userRepository=userRepository;
	}

	public Mono<ServerResponse> all(ServerRequest req){
		//ServerResponse是一个http响应类型，ok()代表200
		//这里body(xx,xx)参数一是异步响应体，参数二是构成响应体的节点
		return ServerResponse.ok().body(userRepository.findAll(), User.class);
	}

	public Mono<ServerResponse> create(ServerRequest req) {
		return req.bodyToMono(User.class)
				.flatMap(user -> this.userRepository.save(user))
				.flatMap(u -> ServerResponse.created(URI.create("/users/" + u.getId())).build());
	}

	public Mono<ServerResponse> get(ServerRequest req) {
		return this.userRepository.findById(req.pathVariable("id"))
				.flatMap(user -> ServerResponse.ok().body(Mono.just(user), User.class))
				.switchIfEmpty(ServerResponse.notFound().build());
	}

	public Mono<ServerResponse> update(ServerRequest req) {

		return Mono
				.zip(
						(data) -> {
							User user = (User) data[0];
							User user_new = (User) data[1];
							user.setName(user_new.getName());
							user.setAge(user_new.getAge());
							return user;
						},
						this.userRepository.findById(req.pathVariable("id")),
						req.bodyToMono(User.class)
						)
				.cast(User.class)
				.flatMap(user -> this.userRepository.save(user))
				.flatMap(user -> ServerResponse.noContent().build());

	}

	public Mono<ServerResponse> delete(ServerRequest req) {
		return ServerResponse.noContent().build(this.userRepository.deleteById(req.pathVariable("id")));
	}

}
